<?php

// Prevent individual file access
if(!defined('DIR_BASE')) exit;

/**
 * Control database interaction
 */
class Database{
	
	/**
	 * Initialize the database with the given params to access
	 * @param String $dbname The database
	 * @param String $host (optional) The host (usually 'localhost')
	 * @param String $user (optional) The username to access
	 * @param String $pass (optional) The password to access
	 */
	public static function init($dbname, $host = '127.0.0.1', $user = 'root', $pass = ''){
		mysql_connect($host, $user, $pass)or die ( mysql_error() );
		mysql_select_db($dbname)or die ( mysql_error() );
	}
	
	/**
	 * Execute a query, and return a result if it is 'selecting'
	 * @param String $qry A query string if you don't want to use the query builder
	 * @param Bool (optional) $firstonly If true then return just a single value of the result, else a whole array
	 * @return String|Array The result of a 'select'-query
	 */
	public static function query($qry, $firstonly = true){
		if(empty($qry))
			return;
		
		$res = array();
		$rtn = mysql_query($qry) or die (htmlspecialchars ($qry.' - '.mysql_error(), ENT_QUOTES));
		if(strtolower(substr($qry, 0, 6)) != 'select')
			return;
		
		if($firstonly) $res = '';
		if(mysql_num_rows($rtn) == 0)
			return $res;
		
		while ($row = mysql_fetch_assoc($rtn)) {
			if($firstonly){
				if(count($row) > 1) // the whole row
					$res = $row; 
				else{
					$row = array_values($row); // one single column
					$res = $row[0];
				}
			}else
				$res[] = $row;
		}
		return $res;
	}
	
	/**
	 * Shortcut of the function 'query' to retrieve an array of records
	 * @see query
	 */
	public static function queryList($qry){
		return self::query($qry, false);
	}
	
	/**
	 * Stop session with the database
	 */
	public static function close(){
		mysql_close();
	}
}

?>